package com.baoteng.rbspy.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mustache.MustacheResourceTemplateLoader;
import org.springframework.stereotype.Service;

import com.baoteng.rbspy.config.car.RbSysConfig;
import com.baoteng.rbspy.config.car.URLConfig;
import com.baoteng.rbspy.model.Model;
import com.baoteng.rbspy.model.privy.CustomerPO;
import com.baoteng.rbspy.model.privy.PersonAddress;
import com.baoteng.rbspy.model.privy.PersonContact;
import com.baoteng.rbspy.model.privy.PersonUpdatePO;
import com.baoteng.rbspy.model.privy.PrivateInfo;
import com.baoteng.rbspy.model.privy.PrivyItemPO;
import com.baoteng.rbspy.model.privy.PrivyPO;
import com.baoteng.rbspy.model.privy.PrivyTokenPO;
import com.baoteng.rbspy.model.privy.group.GoupItemPO;
import com.baoteng.rbspy.model.privy.group.GoupPO;
import com.baoteng.rbspy.model.privy.group.GroupTokenPO;
import com.baoteng.rbspy.model.privy.group.GroupUpdatePO;
import com.baoteng.rbspy.model.privy.group.Taxpayer;
import com.baoteng.rbspy.model.request.CustomerRequest;
import com.baoteng.rbspy.model.request.GroupEditRequest;
import com.baoteng.rbspy.model.request.PrivyEditRequest;
import com.baoteng.rbspy.model.request.PrivyRequest;
import com.baoteng.rbspy.model.request.RenewalDetailsRequest;
import com.baoteng.rbspy.model.response.ResponseModel;
import com.baoteng.rbspy.service.OkHttpClientService;
import com.baoteng.rbspy.service.PrivyService;
import com.baoteng.rbspy.util.BaseUtil;
import com.baoteng.rbspy.util.BeanConvertUtil;
import com.baoteng.rbspy.util.DateUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.samskivert.mustache.Mustache;

@Service
public class PrivyServiceImpl implements PrivyService {

	private final Logger LOGGER = LoggerFactory.getLogger(PrivyServiceImpl.class);

	@Autowired
	OkHttpClientService okHttpClientService;

	@Autowired
	OkHttpClientService noRedirectHttpClient;

	@Autowired
	private Mustache.Compiler compiler;

	@Autowired
	MustacheResourceTemplateLoader mustacheTemplateLoader;

	@Autowired
	URLConfig urlConfig;

	@Autowired
	RbSysConfig rbSysConfig;

	BeanConvertUtil beanUtil = BeanConvertUtil.newInstance();

	public Model<String> checkRepeat(String customerCode,String mobile) {
		ResponseModel<Model<String>> checkResponse = okHttpClientService.getJson(urlConfig.getpersonCheckRepeatUrl()+"?customerCode="
		+(StringUtils.isNotBlank(customerCode)?customerCode:"")+"&phoneNumber="+mobile, new TypeReference<Model<String>>() {});
		return checkResponse.isSuccessful() && checkResponse.getBody() != null ?checkResponse.getBody():null;
	}

	public PrivyPO renewalPrivyInfo(RenewalDetailsRequest request) {
		ResponseModel<PrivyPO> privyResponse = okHttpClientService
				.getHtml(urlConfig.getPrivyUrl() + "?" + beanUtil.convert2RequestURLParam(request), PrivyPO.class);
		return privyResponse.isSuccessful() && privyResponse.getBody() != null ? privyResponse.getBody() : null;
	}

	public String addGroup(GroupEditRequest request) {
		try {
			ResponseModel<GroupTokenPO> token = okHttpClientService.getHtml(urlConfig.getGroupTokenUrl()+"&unifiedSocialCreditCode=",
					GroupTokenPO.class);
			if (token.isSuccessful() && token.getBody() != null && StringUtils.isNotBlank(token.getBody().getToken())) {
				request.setToken(token.getBody().getToken());
//				if(StringUtils.isBlank(request.getProvince())) request.setProvince("440000");
//				if(StringUtils.isBlank(request.getCity())) request.setCity("440100");
//				if(StringUtils.isBlank(request.getArea())) request.setArea("440112");
				String strBody = compiler.compile(mustacheTemplateLoader.getTemplate("group_add")).execute(request);
				ResponseModel<String> addResposne = noRedirectHttpClient.postHtml(urlConfig.getGroupAddUrl(), strBody,
						String.class);
				if (addResposne.isSuccessful() && StringUtils.isNotBlank(addResposne.getBody())) {
					String htmlResponse = addResposne.getBody();
					Matcher match = Pattern.compile("<a[^>]*>(.*?)</a>").matcher(htmlResponse);
					if (match.find()) {
						this.noRedirectHttpClient.getHtml(match.group(1), String.class);
					}
					int startIndex = htmlResponse.indexOf("customerCode=");
					if (startIndex != -1) {
						String customerCode = htmlResponse.substring(startIndex + 13, startIndex + 29);
						if(StringUtils.isNotBlank(customerCode)) {
							if(auditGroup(customerCode,request!=null && request.getContacts()!=null && request.getContacts().size()>0?request.getContacts().get(0).getPhoneType():"")) {
								return customerCode;
							}
						}
					}
					return null;
				}
			}
		} catch (Exception e) {
			LOGGER.error("增加团体客户异常！",e);
		}
		return null;
	}
	
	public boolean auditGroup(String customerCode,String phoneType){
		try {
			String strBody = compiler.compile(mustacheTemplateLoader.getTemplate("group_audit")).execute(phoneType);
			ResponseModel<Model<String>> audit = okHttpClientService.postJson(
					urlConfig.getGroupAuditUrl()+"?customerCode="+customerCode, strBody, new TypeReference<Model<String>>() {
					});
			if(audit.isSuccessful() && audit.getBody()!=null && !Strings.isNullOrEmpty(audit.getBody().getMsg())) {
				if("1".equals(audit.getBody().getMsg())) {
					LOGGER.info(customerCode);
					return true;
				}else {
					LOGGER.error("该客户已经被{}提交人工审批，不允许再次提交人工审批！",audit.getBody().getMsg());
				}
			}
		} catch (Exception e) {
			LOGGER.error("团体客户提交审批异常！",e);
		}
		return false;
	}
	
	public String updGroup(GroupEditRequest request) {
		try {
			ResponseModel<GroupUpdatePO> response = okHttpClientService.getHtml(
					urlConfig.getGroupUpdTokenUrl() + "?syscode=prpall&customerCode=" + request.getCustomerCode(),
					GroupUpdatePO.class);
			if (response.isSuccessful() && response.getBody() != null
					&& StringUtils.isNotBlank(response.getBody().getToken())) {
				GroupUpdatePO po = response.getBody();
				StringBuilder submitDesc = new StringBuilder();
				if(!request.getUnifiedSocialCreditCode().equals(po.getUnifiedSocialCreditCode())) {
					submitDesc.append("原组织机构代码：");
					submitDesc.append(po.getUnifiedSocialCreditCode());
					po.setUnifiedSocialCreditCode(request.getUnifiedSocialCreditCode());
					po.setCreditDateValid("2199-12-31");
					submitDesc.append("修改为：");
					submitDesc.append(po.getUnifiedSocialCreditCode());
				}
				if(request.getOrganizeCode()!=null && !request.getOrganizeCode().equals(po.getOrganizeCode())) {
					submitDesc.append("原统一社会信用代码：");
					submitDesc.append(po.getOrganizeCode());
					po.setOrganizeCode(request.getOrganizeCode());
					po.setOrgDateValid("2199-12-31");
					submitDesc.append("修改为：");
					submitDesc.append(po.getUnifiedSocialCreditCode());
				}
				if(!request.getCustomerCName().equals(po.getCustomerCName())) {
					submitDesc.append("原客户名称：");
					submitDesc.append(po.getCustomerCName());
					po.setCustomerCName(request.getCustomerCName());
					submitDesc.append("修改为：");
					submitDesc.append(po.getCustomerCName());
				}
				if(submitDesc.length()>0) {
					po.setSubmitDescription(submitDesc.toString());
				}
				
				if(request.getTax()!=null && "2".equals(request.getTax().getTaxType()) && (po.getTaxpayer()==null || StringUtils.isBlank(po.getTaxpayer().getOldTaxPayerType()))) {
					if(po.getTaxpayer()==null) {
						po.setTaxpayer(new Taxpayer());
						po.setCustomerCode(request.getCustomerCode());
					}
					Taxpayer tax = po.getTaxpayer();
					tax.setAccount(request.getTax().getAccount());
					tax.setAddress(request.getTax().getAddress());
					tax.setBankView(request.getTax().getBank());
					tax.setPhoneNumber1(request.getTax().getPhone());
					tax.setPhoneNumber(BaseUtil.encodeRbPhoneMobile(request.getTax().getPhone()));
					tax.setTaxPayerType("1");
					tax.setRevenueCode(request.getTax().getIdNo());
					tax.setSubmitDescription("新增纳税人信息，请审批。");
				}
				
				if (po.getContacts() == null || po.getContacts().size() == 0) {
					
					if (po.getContacts() == null)
						po.setContacts(Lists.newArrayList());
					
					PersonContact contact = request.getContacts()!=null && request.getContacts().size()>0?request.getContacts().get(0):new PersonContact();
					contact.setPhoneGroupAddNo(1);
					contact.setIdNewPhoneFlag("new");
					contact.setPhoneNumberView(Optional.ofNullable(contact.getPhoneNumberView()).orElse(BaseUtil.getRandomMobile()));
					contact.setPhoneNumber(BaseUtil.encodeRbPhoneMobile(contact.getPhoneNumberView()));
					contact.setPhoneType(Optional.ofNullable(contact.getPhoneType()).orElse("1"));
					contact.setPhoneproperties("01");
					contact.setPhonevalidstatus("1");
					contact.setIsDefault("0");
					po.getContacts().add(contact);
				}else {
					PersonContact contact = request.getContacts()!=null && request.getContacts().size()>0?request.getContacts().get(0):null;
					po.getContacts().forEach(c->{
						if(StringUtils.isBlank(c.getPhoneNumber()) || (!StringUtils.isNumeric(c.getPhoneNumber()) || (c.getPhoneNumber().length()>=7 && c.getPhoneNumber().length()<=12))) {
							c.setPhoneNumberView(contact!=null?contact.getPhoneNumber():BaseUtil.getRandomMobile());
							c.setPhoneNumber(BaseUtil.encodeRbPhoneMobile(c.getPhoneNumberView()));
							if("2".equals(c.getPhoneType())) {
								c.setPhoneNumberView(BaseUtil.getRandomTel("020"));
								c.setPhoneNumber(BaseUtil.encodeRbPhoneMobile(c.getPhoneNumberView()));
							}
						}
						c.setPhonevalidstatus("1");
						c.setPhoneproperties("01");
					});
				}
				if (po.getAddresses() != null && po.getAddresses().size() >0) {
					PersonAddress _address = request.getAddresses()!=null && request.getAddresses().size()>0?request.getAddresses().get(0):null;
					for (PersonAddress address : po.getAddresses()) {
						if (!"1".equals(address.getAddressvalidstatus())) {
							address.setAddressvalidstatus("1");
						}
						if(StringUtils.isBlank(address.getAddresscname())) {
							address.setAddresscname(_address!=null?_address.getAddresscname():"广州市天河区");
						}
						if(StringUtils.isBlank(address.getProvince())) address.setProvince("440000");
						address.setCity(address.getProvince().substring(0, 2)+"0100");
						address.setArea(address.getCity().substring(0,4)+"01");
					}
				} else{
					PersonAddress address = new PersonAddress();
					// 广州黄浦区，默认值
					address.setProvince("440000");
					address.setCity("440100");
					address.setArea("440101");
					address.setAddresscname(request.getAddresses()!=null && request.getAddresses().size()>0?request.getAddresses().get(0).getAddresscname():"广州市天河区");
					address.setAdressPersonAddNo(1);
					address.setAdresstype(1);
					address.setAddressvalidstatus("1'");
					address.setIsAddressDefault("1");
					po.setAddresses(Lists.newArrayList(address));
				}
				String strBody = compiler.compile(mustacheTemplateLoader.getTemplate("group_upd")).execute(po);
				ResponseModel<String> updateResposne = noRedirectHttpClient.postHtml(urlConfig.getGroupUpdUrl(),
						strBody, String.class);
				if (updateResposne.isSuccessful() && StringUtils.isNotBlank(updateResposne.getBody())) {
					String htmlResponse = updateResposne.getBody();
					Elements doc = Jsoup.parse(htmlResponse).select("a");
					if(doc!=null && doc.size()>0) {
						String url = doc.attr("href");
						ResponseModel<String> findCustomer = this.okHttpClientService.getHtml(url, String.class);
						if(findCustomer.isSuccessful()) {
							if(auditGroup(request.getCustomerCode(),request!=null && request.getContacts()!=null && request.getContacts().size()>0?request.getContacts().get(0).getPhoneType():"")) {
								LOGGER.info("PrivyServiceImpl updateGroup success.");
								return request.getCustomerCode();
							}
						}
					}
					LOGGER.error("PrivyServiceImpl updateGroup fail.");
					return null;
				}
			}
		} catch (Exception e) {
			LOGGER.error("PrivyServiceImpl updateGroup fail.", e);
		}
		return null;
	}
	
	public GoupItemPO getGroupInfo(PrivyRequest request) {
		Preconditions.checkNotNull(request);
		Preconditions.checkNotNull(request.get_insuredName());
		request.set_insuredCode(Optional.ofNullable(request.get_insuredCode()).orElse(""));
		request.setUnifiedSocialCreditCode(Optional.ofNullable(request.getUnifiedSocialCreditCode()).orElse(""));
//		String name = request.get_insuredName();
		request.set_insuredName("");
		ResponseModel<Model<GoupItemPO>> groupResponse = okHttpClientService.getJson(
				urlConfig.getGroupQueryUrl() + "?" + beanUtil.convert2RequestURLParam(request),
				new TypeReference<Model<GoupItemPO>>() {
				});
		if (groupResponse.isSuccessful() && groupResponse.getBody() != null && groupResponse.getBody().getData() != null
				&& !groupResponse.getBody().getData().isEmpty()) {
			GoupItemPO po = groupResponse.getBody().getData().get(0);
			if (po.getCount() == null || po.getCount() == 0) {
				return null;
			}else if (po.getCount() == 1 ) {
				return po;
			} 
		}
		return null;
	}
	
	public List<GoupPO> listGroupInfo(CustomerRequest request) {
		try {
			String strBody = compiler.compile(mustacheTemplateLoader.getTemplate("group_query")).execute(request);
//			String strParam = beanUtil.convert2RequestURLParam(request);
			ResponseModel<Model<GoupPO>> groupResponse = okHttpClientService.postJson(
					urlConfig.getGroupListUrl() + "?pageSize=20&pageNo=1" , strBody, new TypeReference<Model<GoupPO>>() {
					});
			if (groupResponse.isSuccessful()) {
				return groupResponse.getBody() != null ? groupResponse.getBody().getData() : null;
			} else {
				groupResponse = okHttpClientService.postJson(urlConfig.getGroupListUrl() + "?pageSize=20&pageNo=1", strBody,
						new TypeReference<Model<GoupPO>>() {
						});
			}
			return groupResponse.isSuccessful() && groupResponse.getBody() != null ? groupResponse.getBody().getData()
					: null;
		} catch (Exception e) {
			LOGGER.error("PrivyServiceImpl listGroupInfo fail.", e);
		}
		return null;
	}
	
	public PrivyItemPO getPrivyInfo(PrivyRequest request) {
		Preconditions.checkNotNull(request);
		Preconditions.checkNotNull(request.get_insuredName());
		request.set_insuredCode(Optional.ofNullable(request.get_insuredCode()).orElse(""));
//		String name = request.get_insuredName();
		request.set_insuredName("");
		ResponseModel<Model<PrivyItemPO>> privyResponse = okHttpClientService.getJson(
				urlConfig.getPrivyQueryUrl() + "?" + beanUtil.convert2RequestURLParam(request),
				new TypeReference<Model<PrivyItemPO>>() {
				});
		if (privyResponse.isSuccessful() && privyResponse.getBody() != null && privyResponse.getBody().getData() != null
				&& !privyResponse.getBody().getData().isEmpty()) {
			PrivyItemPO po = privyResponse.getBody().getData().get(0);
			if (po.getCount() == null || po.getCount() == 0) {
				return null;
			}
			if (po.getCount() == 1 ) {
				return po;
			} else {
				CustomerRequest _request = new CustomerRequest();
				_request.setIdentifyNumber(request.get_identifyNumber());
				_request.setIdentifyType(request.get_identifyType());
				List<CustomerPO> customers = getCustomerInfo(_request);
				if (customers != null) {
					for (CustomerPO _po : customers) {
						if ("2".equals(_po.getAuditStatus())) {
							PrivyItemPO privy = new PrivyItemPO();
							privy.setInsuredCode(_po.getCustomerCode());
							privy.setIdentifyNumber(request.get_identifyNumber());
							privy.setIdentifyType(request.get_identifyType());
							privy.setInsuredName(_po.getCustomerCName());
							privy.setEmail(_po.getEmail());
							privy.setSex(_po.getGender());
							privy.setVersionNo(_po.getVersionNo());
							privy.setPhoneNumber(_po.getPhoneNumber());
							privy.setMobile(getPrivateMobile(_po));
							privy.setMobileNoYG(_po.getCustomMobile());
							privy.setInsuredAddress(_po.getAddressCName());
							privy.setAuditStatus(_po.getAuditStatus());
							privy.setCountryCode(_po.getNationality());
							privy.setGroupCode(_po.getGroupCode());
							privy.setUnitType(_po.getBusinessSort());
							privy.setPostCode(_po.getPostCode());
							return privy;
						}
					}
				}
			}
		}
		return null;
	}

	public String getPrivateMobile(CustomerPO po) {
		String secret = String.join(",", po.getCustomerCode(),
				// po.getCustomerCName()
				"", po.getIdentifyType(), po.getIdentifyNumber(), po.getGender(), po.getNationality(),
				po.getBusinessSort(), po.getCustomMobile(), po.getPhoneNumber(),
				// po.getAddressCName()
				"", po.getPostCode(), po.getAuditStatus(),
				po.getVersionNo() != null ? String.valueOf(po.getVersionNo()) : "", po.getGroupCode(),
				po.getCustomerEName(), po.getResident(),
				StringUtils.isNotBlank(rbSysConfig.getComCode()) && rbSysConfig.getComCode().startsWith("45")
						? po.getPhoneRepeatCheckFlag() + po.getPhonePropertiesRepeatCheckFlag()
								+ po.getPhoneTypeRepeatCheckFlag() + po.getConfigedRepeatTimes()
								+ po.getPhoneNumberRepeatTimes()
						: ",,,,",
				StringUtils.isNotBlank(rbSysConfig.getComCode()) && rbSysConfig.getComCode().startsWith("11")
						? po.getEmail()
						: "",
				"");
		ResponseModel<PrivateInfo> pResponse = okHttpClientService.getHtml(
				urlConfig.getPrivyMobileUrl() + "?person=" + secret.replaceAll("null", "").replaceAll(" ", ""),
				PrivateInfo.class);
		if (pResponse.isSuccessful() && pResponse.getBody() != null
				&& StringUtils.isNotBlank(pResponse.getBody().getPrivateMobile())) {
			String _mobile = pResponse.getBody().getPrivateMobile();
			int last = _mobile.lastIndexOf(",");
			return last > 0 ? _mobile.substring(last + 1) : null;
		}
		return null;
	}

	public List<CustomerPO> getCustomerInfo(CustomerRequest request) {
		try {
			String strBody = compiler.compile(mustacheTemplateLoader.getTemplate("custom_query")).execute(request);
//			String strParam = beanUtil.convert2RequestURLParam(request);
			ResponseModel<Model<CustomerPO>> privyResponse = okHttpClientService.postJson(
					urlConfig.getPrivyListUrl() + "?pageSize=20&pageNo=1", strBody, new TypeReference<Model<CustomerPO>>() {
					});
			if (privyResponse.isSuccessful()) {
				return privyResponse.getBody() != null ? privyResponse.getBody().getData() : null;
			} else {
				privyResponse = okHttpClientService.postJson(urlConfig.getPrivyListUrl() + "?pageSize=20&pageNo=1", strBody,
						new TypeReference<Model<CustomerPO>>() {
						});
			}
			return privyResponse.isSuccessful() && privyResponse.getBody() != null ? privyResponse.getBody().getData()
					: null;
		} catch (Exception e) {
			LOGGER.error("PrivyServiceImpl getCustomerInfo fail.", e);
		}
		return null;
	}

	public String addPerson(PrivyEditRequest request) {
		try {
			ResponseModel<PrivyTokenPO> token = okHttpClientService.getHtml(urlConfig.getPersoTokenUrl(),
					PrivyTokenPO.class);
			if (token.isSuccessful() && token.getBody() != null && StringUtils.isNotBlank(token.getBody().getToken())) {
				request.setToken(token.getBody().getToken());
				if(StringUtils.isBlank(request.getProvince())) request.setProvince("440000");
				request.setCity(request.getProvince().substring(0, 2)+"0100");
				request.setArea(request.getCity().substring(0,4)+"01");
				
				String strBody = compiler.compile(mustacheTemplateLoader.getTemplate("person_add")).execute(request);
				// strBody= strBody.replaceAll("(\r\n|\r|\n|\n\r)", "");
				// String
				// strBody="struts.token.name=token&token="+token.getBody().getToken()+"&syscode=prpall&searchType=&checkFlag=&prpDcustomerPerson.validStatus=1&prpDcustomerPerson.customerCode=&prpDcustomerPerson.versionNo=0&prpDcustomerPerson.customerCName=%D6%EC%B2%A8&prpDcustomerPerson.customerFullEName=&prpDcustomerPerson.identifyType=01&prpDcustomerPerson.identifyNumber="+
				// request.getIdentifyNumber()+"&prpDcustomerPerson.gender=1&prpDcustomerPerson.birthDate=1980-04-03&prpDcustomerPerson.nationality=CHN&country=%D6%D0%B9%FA&prpDcustomerPerson.dateValid=2199-12-30&prpDcustomerPerson.resident=A&prpDcustomerPerson.financeFlag=0&prpDcustomerRisk.creditLevel=3&prpDcustomerPerson.marriage=&prpDcustomerPerson.favourite=&prpDcustomerPerson.educationCode=&prpDcustomerPerson.health=&prpDcustomerPerson.stature=&prpDcustomerPerson.weight=&prpDcustomerPerson.bloodType=&prpDcustomerPerson.deathDate=&prpDcustomerPerson.customerKind=&prpDcustomerPerson.auditType=%D0%C2%D4%F6&prpDcustomerPerson.submitDescription=%09%09%09%09%09%09%09%09%0D%0A%09%09%09%09%09%09%09&PhonePersonNo=1&phoneNumber1=&phoneType2=&bondingDate=&bondingReason=&bondingPerson=&bondingOrganization=&bondingApply=&removebondingApply=&bondingFlag=&phoneType=1&phoneNumber=13568827999&phoneproperties=01&customerRelations=&bestRelationDT=&phonevalidstatus=1&isDefault=0&PhonePersonNo=&phoneNumber1=&phoneType2=&bondingDate=&bondingReason=&bondingPerson=&bondingOrganization=&bondingApply=&removebondingApply=&bondingFlag=&phoneType=1&phoneNumber=&phoneproperties=01&customerRelations=&bestRelationDT=&phonevalidstatus=1&isDefault=&AddressPersonNo=1&adresstype=1&province=&city=&area=&addresscname=%B9%E3%D6%DD%CC%EC%BA%D3&addressename=&postcode=&addressvalidstatus=1&isAddressDefault=0&AddressPersonNo=&adresstype=1&province=&city=&area=&addresscname=&addressename=&postcode=&addressvalidstatus=1&isAddressDefault=&prpDcustomerPerson.email=&prpDcustomerPerson.imType=&prpDcustomerPerson.imNo=&prpDcustomerPerson.weiChat=&prpDcustomerPerson.qq=&prpDcustomerPerson.selfMonthIncome=&prpDcustomerPerson.selfMonthIncomeCurrency=CNY&prpDcustomerPerson.familyMonthIncome=&prpDcustomerPerson.familyMonthIncomeCurrency=CNY&FamliyPersonNo=&relationType1=&name1=&birthDate1=&identifyNumber1=&unit1=&duty1=&phoneType1=&phone1=&AccountPersonNo=&bank=&bankView=&branchBank=&account=&accountType=&accountvaildstatus=1&mainAccountValid=&UnitPersonNo=&unitType=&unit=&unitAddress=&occupationCode=&occupationCodeView=&dutyLevel=&dutyStatus=&prpDcustomerPerson.agriFlag=0&prpDcstprf.comCitycode=&prpDcstprf.comCountycode=&prpDcstprf.salsDepartcode=&prpDcstprf.serStationcode=&prpDcstprf.serPointcode=&prpDcstprf.famliyMembersno=&prpDcstprf.ageLt18no=&prpDcstprf.ageGt65no=&prpDcstprf.cultivatedLand=&prpDcstprf.workerQuantity=&prpDcstprf.woodLand=&prpDcstprf.pigNum=&prpDcstprf.cattleNum=&prpDcstprf.sheepNum=&prpDcstprf.otherNum=&prpDcstprf.bankNo=&prpDcstprf.accountName=&prpDcstprf.bankName=&prpDcstprf.householdIncome=&prpDcstprf.houseNum=&prpDcstprf.buildStructure=&prpDcstprf.liaisonmanCode=&prpDcstprf.liaisonmanName=&prpDcstprf.chargePersonCode=&prpDcstprf.chargePersonName=&prpDcstprf.describes=&CarPersonNo=&licenseNo=&vehicleName=&engineNo=&vinNo=&enrollDate=&policyEndDate=&insureCompany=";
				ResponseModel<String> addResposne = noRedirectHttpClient.postHtml(urlConfig.getPersonAddUrl(), strBody,
						String.class);
				if (addResposne.isSuccessful() && StringUtils.isNotBlank(addResposne.getBody())) {
					String htmlResponse = addResposne.getBody();
					Matcher match = Pattern.compile("<a[^>]*>(.*?)</a>").matcher(htmlResponse);
					if (match.find()) {
						this.noRedirectHttpClient.getHtml(match.group(1), String.class);
					}
					int startIndex = htmlResponse.indexOf("customerCode=");
					if (startIndex != -1) {
						String customerCode = htmlResponse.substring(startIndex + 13, startIndex + 29);
						LOGGER.info(customerCode);
						return customerCode;
					}

					return null;
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	public String updatePerson(PrivyEditRequest request) {
		try {
			ResponseModel<PersonUpdatePO> response = okHttpClientService.getHtml(
					urlConfig.getPersoUpdTokenUrl() + "?syscode=prpall&customerCode=" + request.getCustomerCode(),
					PersonUpdatePO.class);
			if (response.isSuccessful() && response.getBody() != null
					&& StringUtils.isNotBlank(response.getBody().getToken())) {
				PersonUpdatePO po = response.getBody();
				if (StringUtils.isBlank(po.getDateValid())) {
					po.setDateValid("2099-12-30");
					po.setSubmitDescription("修改身份证信息");
				} else if (DateUtils.parseDateByFormat(po.getDateValid(), "yyyy-MM-dd").compareTo(new Date()) <= 0) {
					po.setDateValid("2099-12-30");
					po.setSubmitDescription("修改身份证信息");
				}
				if(StringUtils.isNotBlank(request.getCustomerCName())) {
					po.setCustomerCName(request.getCustomerCName());
				}
				if (po.getContacts() == null || po.getContacts().size() == 0) {
					if (po.getContacts() == null)
						po.setContacts(Lists.newArrayList());
					PersonContact contact = new PersonContact();
					contact.setPhonePersonAddNo(1);
					contact.setIdNewPhoneFlag("new");
					contact.setPhoneNumberView(request.getPhoneNumber());
					contact.setPhoneNumber(BaseUtil.encodeRbPhoneMobile(request.getPhoneNumber()));
					contact.setPhoneType("1");
					contact.setPhoneproperties("01");
					contact.setPhonevalidstatus("1");
					contact.setIsDefault("1");
					po.getContacts().add(contact);
				}else {
					po.getContacts().forEach(c->{
						if(StringUtils.isBlank(c.getPhoneNumber()) || (!StringUtils.isNumeric(c.getPhoneNumber()) || (c.getPhoneNumber().length()>=7 && c.getPhoneNumber().length()<=12))) {
							c.setPhoneNumberView(request.getPhoneNumber());
							c.setPhoneNumber(BaseUtil.encodeRbPhoneMobile(request.getPhoneNumber()));
							if("2".equals(c.getPhoneType())) {
								c.setPhoneNumberView(BaseUtil.getRandomTel("020"));
								c.setPhoneNumber(BaseUtil.encodeRbPhoneMobile(c.getPhoneNumberView()));
							}
						}
						c.setPhonevalidstatus("1");
						c.setPhoneproperties("01");
					});
				}
				if (po.getAddresses() != null && po.getAddresses().size() >0) {
					for (PersonAddress address : po.getAddresses()) {
						if (!"1".equals(address.getAddressvalidstatus())) {
							address.setAddressvalidstatus("1");
						}
						if(StringUtils.isBlank(address.getAddresscname())) {
							address.setAddresscname(request.getAddresscname());
						}
						if (StringUtils.isBlank(address.getProvince()) || StringUtils.isBlank(address.getCity())
								|| StringUtils.isBlank(address.getArea())) {
							address.setProvince("440000");
							address.setCity("440100");
							address.setArea("440101");
						}
					}
				} else{
					PersonAddress address = new PersonAddress();
					// 广州黄浦区，默认值
					address.setProvince("440000");
					address.setCity("440100");
					address.setArea("440101");
					address.setAddresscname(request.getAddresscname());
					address.setAdressPersonAddNo(1);
					address.setAdresstype(1);
					address.setAddressvalidstatus("1'");
					address.setIsAddressDefault("1");
					po.setAddresses(Lists.newArrayList(address));
				}
				String strBody = compiler.compile(mustacheTemplateLoader.getTemplate("person_upd")).execute(po);
				ResponseModel<String> updateResposne = noRedirectHttpClient.postHtml(urlConfig.getPersonUpdUrl(),
						strBody, String.class);
				if (updateResposne.isSuccessful() && StringUtils.isNotBlank(updateResposne.getBody())) {
					String htmlResponse = updateResposne.getBody();
					Elements doc = Jsoup.parse(htmlResponse).select("a");
					if(doc!=null && doc.size()>0) {
						String url = doc.attr("href");
						this.okHttpClientService.getHtml(url, String.class);
					}
					int startIndex = htmlResponse.indexOf("customerCode=");
					if (startIndex != -1) {
						String customerCode = htmlResponse.substring(startIndex + 13, startIndex + 29);
						LOGGER.info(customerCode);

						return request.getCustomerCode();
					}
					return null;
				}
			}
		} catch (Exception e) {
			LOGGER.error("PrivyServiceImpl updatePerson fail.", e);
		}
		return null;
	}

	public String addCustomer(PrivyEditRequest request) {
		return addPerson(request);
	}

	public String updateCustomer(PrivyEditRequest request) {
		return updatePerson(request);
	}

}
